package com.tanhua.server.service;

import cn.hutool.core.util.StrUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.common.vo.ErrorResult;
import com.tanhua.dubbo.api.SoundApi;
import com.tanhua.dubbo.pojo.Sound;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Service
@Slf4j
public class SoundService {

    @Autowired
    protected FastFileStorageClient storageClient;  //上传sound

    @Autowired
    private FdfsWebServer fdfsWebServer;

    @DubboReference(version = "1.0.0")
    private SoundApi soundApi;

    @Autowired
    private SoundMQService soudMQService;  //发布后的信息提示


    public Object saveSound(MultipartFile soundFile){
        try {
        Sound sound = new Sound();
        sound.setUserId(UserThreadLocal.get());

        //上传语音文件

            StorePath storePath = this.storageClient.uploadFile(soundFile.getInputStream(),
                    soundFile.getSize(), StrUtil.subAfter(soundFile.getOriginalFilename(),
                            '.', true), null);

            String soundPath=fdfsWebServer.getWebServerUrl()+storePath.getFullPath();
            sound.setSoundUrl(soundPath);

            String soundId=this.soundApi.saveSound(sound);

            if (StrUtil.isNotEmpty(soundId)){
                //发送消息
                this.soudMQService.soundMsg(soundId);
                return null;
            }
        } catch (IOException e) {
          log.error("发布语音失败",e);

        }
        return ErrorResult.builder()
                .errCode("5001")
                .errMessage("发布语音失败");
    }
}
